package com.changgou.oauth.controller;

import com.changgou.oauth.service.UserLoginService;
import com.changgou.oauth.util.AuthToken;
import entity.Result;
import entity.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.util.Map;


/**
 * @ClassName UserLoginController
 * @Description
 * @Author Mr.L
 * @Date 13:52 2019/11/22
 * @Version 2.1
 **/
@RestController
@RequestMapping("/user")
public class UserLoginController {

    @Value("${auth.clientId}")
    private String clientId;

    @Value("${auth.clientSecret}")
    private String clientSecret;

    @Autowired
    private UserLoginService userLoginService;

    /**
     * 用户登录
     * @param username
     * @param password
     * @return
     */
    @RequestMapping("/login")
    public Result login(String username, String password, HttpServletResponse response){
        try {
            // 授权模式：密码授权
            String grant_type = "password";
            // 登录认证
//          AuthToken authToken = userLoginService.login(clientId, clientSecret, username, password, grant_type);
            AuthToken authToken = userLoginService.login(username, password,clientId, clientSecret,  grant_type);

            Cookie cookie = new Cookie("Authorization",authToken.getAccessToken());
            cookie.setDomain("localhost");
            cookie.setPath("/");
            response.addCookie(cookie);
            return new Result(true, StatusCode.OK, "登录成功", cookie);
        } catch (Exception e) {
            e.printStackTrace();
        }
//        String token = authToken.getAccessToken();
        // 注意：这里的token并没有bearer字符串，在过滤哪里需要拼接
        return new Result(true, StatusCode.OK, "登录失败");
    }
}
